package com.pengcheng.hnweb.interceptor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pengcheng.hnweb.service.DbService;
import com.pengcheng.hnweb.util.Common;
import com.pengcheng.hnweb.util.FileUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class Saveinterceptor  implements HandlerInterceptor {
    @Autowired
    private Common common;
    @Autowired
    private DbService dbService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private FileUtil fileUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("saveinterceptor");
        String table=request.getParameter("table");
        String str_row=request.getParameter("row");
        if(common.is_empty(table)||common.is_empty(str_row))
        {
            return false;
        }
        ObjectMapper mapper=new ObjectMapper();
        Map<String,Object> res=new HashMap<>();
        try {
            // 将JSON字符串转换为Map对象
            Map<String, Object> map = mapper.readValue(str_row, new TypeReference<Map<String, Object>>() {});
            if(table.equals("field"))
            {

            }
            else if(table.equals("target"))
            {
                Object id=map.get("id");
                Object year=map.get("year");
                if(year!=null)
                {
                    String sql="select * from hnww_target where deleted=0 and year="+year.toString();
                    List<Map<String,Object>> rows_target=jdbcTemplate.queryForList(sql);
                    if(rows_target!=null&&rows_target.size()>0)
                    {
                        if(id==null)
                        {
                            res.put("code",0);
                            res.put("msg", "已存在相同年份的用水目标");
                            response.setCharacterEncoding("UTF-8");
                            response.setContentType("text/html");
                            response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                            return false;
                        }
                        else if(rows_target.size()==1)
                        {
                            if(!rows_target.get(0).get("id").toString().equals(id.toString()))
                            {
                                res.put("code",0);
                                res.put("msg", "已存在相同年份的用水目标");
                                response.setCharacterEncoding("UTF-8");
                                response.setContentType("text/html");
                                response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                                return false;
                            }
                        }
                        else {
                            res.put("code",0);
                            res.put("msg", "已存在相同年份的用水目标");
                            response.setCharacterEncoding("UTF-8");
                            response.setContentType("text/html");
                            response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                            return false;
                        }
                    }
                }
            }
            else if(table.equals("feestep"))
            {
                Object id=map.get("id");
                Object name=map.get("name");
                Object is_default=map.get("is_default");
                Object percents=map.get("percents");
                Object prices=map.get("prices");
                if(name==null||name.toString().equals(""))
                {
                    res.put("code",0);
                    res.put("msg", "名称不可为空");
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                    return false;
                }
                if(is_default==null||is_default.toString().equals(""))
                {
                    res.put("code",0);
                    res.put("msg", "是否默认不可为空");
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                    return false;
                }
                if(percents==null||percents.toString().equals(""))
                {
                    res.put("code",0);
                    res.put("msg", "超额比例不可为空");
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                    return false;
                }
                if(prices==null||prices.toString().equals(""))
                {
                    res.put("code",0);
                    res.put("msg", "超额费用不可为空");
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                    return false;
                }
                String[] list_percent=percents.toString().split(",");
                String[] list_price=prices.toString().split(",");
                if(list_price.length!=(list_percent.length+1))
                {
                    res.put("code",0);
                    res.put("msg", "超额费用的个数应该比超额比例的个数大1");
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                    return false;
                }
                for(int i=0;i<list_percent.length;i++)
                {
                    String percent=list_percent[i];
                    if(!common.is_number(percent))
                    {
                        res.put("code",0);
                        res.put("msg", "超额比例中"+percent+"必须为数字");
                        response.setCharacterEncoding("UTF-8");
                        response.setContentType("text/html");
                        response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                        return false;
                    }
                }
                for(int i=0;i<list_price.length;i++)
                {
                    String percent=list_price[i];
                    if(!common.is_number(percent))
                    {
                        res.put("code",0);
                        res.put("msg", "超额费用中"+percent+"必须为数字");
                        response.setCharacterEncoding("UTF-8");
                        response.setContentType("text/html");
                        response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                        return false;
                    }
                }
                if(is_default.toString().equals("1")||is_default.toString().equals("0"))
                {
                    if(is_default.toString().equals("0"))
                    {
                        String sql="update hnww_feestep set is_default=0";
                        jdbcTemplate.update(sql);
                    }
                }
                else {
                    res.put("code",0);
                    res.put("msg", "是否默认必须为0或1");
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                    return false;
                }
            }
            else if(table.equals("resource"))
            {
                Object id=map.get("id");
                Object name=map.get("name");
                Object is_default=map.get("is_default");
                Object percents=map.get("percents");
                Object prices=map.get("prices");
                Object deleted=map.get("deleted");
                //如果deleted=1，id！=null，则表示删除，这时候检查，水资源站点下方是否有设备，如果有则不能删除
                if(id!=null&&deleted!=null)
                {
                    if("1".equals(deleted+""))
                    {
                        //查询关联的设备
                        String sql="select * from hnww_device where deleted=0 and dtype=1 and detail_id="+id;
                        List<Map<String,Object>> rows_device=jdbcTemplate.queryForList(sql);
                        if(rows_device!=null&&rows_device.size()>0)
                        {
                            res.put("code",0);
                            res.put("msg", "请删除水资源站点关联设备后再试");
                            response.setCharacterEncoding("UTF-8");
                            response.setContentType("text/html");
                            response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                            return false;
                        }
                    }
                }
            }
            else if(table.equals("site"))
            {
                Object id=map.get("id");
                Object name=map.get("name");
                Object is_default=map.get("is_default");
                Object percents=map.get("percents");
                Object prices=map.get("prices");
                Object deleted=map.get("deleted");
                //如果deleted=1，id！=null，则表示删除，这时候检查，水资源站点下方是否有设备，如果有则不能删除
                if(id!=null&&deleted!=null)
                {
                    if("1".equals(deleted+""))
                    {
                        //查询关联的设备
                        String sql="select * from hnww_device where deleted=0 and dtype=0 and detail_id="+id;
                        List<Map<String,Object>> rows_device=jdbcTemplate.queryForList(sql);
                        if(rows_device!=null&&rows_device.size()>0)
                        {
                            res.put("code",0);
                            res.put("msg", "请删除用水单位关联设备后再试");
                            response.setCharacterEncoding("UTF-8");
                            response.setContentType("text/html");
                            response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                            return false;
                        }
                    }
                }
                String sql="";
                Object fnumber=map.get("field_130");
                //如果deleted=1，id！=null，则表示删除，这时候检查，水资源站点下方是否有设备，如果有则不能删除
                if(deleted!=null&&deleted.toString().equals("1"))
                {
                }
                else if(fnumber!=null&&!"".equals(fnumber+""))
                {
                    if(id!=null)
                    {
                        sql="select * from "+dbService.prefix+"_site where field_130=? and deleted=0 and id!=?";
                        List<Map<String,Object>> list_permit=jdbcTemplate.queryForList(sql,new Object[]{fnumber,Integer.parseInt(id.toString())});
                        if(list_permit.size()>0)
                        {
                            res.put("code",0);
                            res.put("msg", "存在相同许可证号的信息");
                            response.setCharacterEncoding("UTF-8");
                            response.setContentType("text/html");
                            response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                            return false;
                        }
                    }
                    else {
                        sql="select * from "+dbService.prefix+"_permit where fnumber=? and deleted=0";
                        List<Map<String,Object>> list_permit=jdbcTemplate.queryForList(sql,new Object[]{fnumber});
                        if(list_permit.size()>0)
                        {
                            res.put("code",0);
                            res.put("msg", "存在相同许可证号的信息");
                            response.setCharacterEncoding("UTF-8");
                            response.setContentType("text/html");
                            response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                            return false;
                        }
                    }
                }
            }
            else if(table.equals("permit"))
            {
                String sql="";
                Object id=map.get("id");
                Object fnumber=map.get("fnumber");
                Object deleted=map.get("deleted");
                //如果deleted=1，id！=null，则表示删除，这时候检查，水资源站点下方是否有设备，如果有则不能删除
                if(deleted!=null&&deleted.toString().equals("1"))
                {
                }
                else
                {
                    if(id!=null)
                    {
                        sql="select * from "+dbService.prefix+"_permit where fnumber=? and deleted=0 and id!=?";
                        List<Map<String,Object>> list_permit=jdbcTemplate.queryForList(sql,new Object[]{fnumber,Integer.parseInt(id.toString())});
                        if(list_permit.size()>0)
                        {
                            res.put("code",0);
                            res.put("msg", "存在相同许可证号的信息");
                            response.setCharacterEncoding("UTF-8");
                            response.setContentType("text/html");
                            response.getWriter().write(new ObjectMapper().writeValueAsString(res));
                            return false;
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);log.info("saveinterceptor");
    }

    public Map<String,Object> after(String table,Map<String,Object> row,Map<String,Object> res)
    {
        try {
            if(table.equals("field")&&row.get("id")!=null)
            {
                String sql1="select * from "+dbService.prefix+"_field where id=?";
                List<Map<String,Object>> list_field=jdbcTemplate.queryForList(sql1,new Object[]{Integer.parseInt(row.get("id")+"")});
                if(list_field.size()==1)
                {
                    Object ftype=list_field.get(0).get("ftype");
                    int id=Integer.parseInt(list_field.get(0).get("id")+"");
                    if(ftype!=null)
                    {
                        fileUtil.add_msg("save_after",ftype.toString()+":"+id);
                        if(ftype.toString().equals("1"))
                        {
                            String t="site";
                            List<Map<String,Object>> columns=dbService.columns(t);
                            int index=-1;
                            for(int i=0;i<columns.size();i++)
                            {
                                String field=columns.get(i).get("Field").toString();
                                if(field.equals("field_"+id))
                                {
                                    index=i;
                                    i=columns.size();
                                }
                            }
                            if(index==-1)
                            {
                                //用水站点
                                String sql="ALTER table hnww_site add COLUMN field_"+id+" varchar(200) not null default ''";
                                jdbcTemplate.update(sql);
                            }
                        }
                        if(ftype.toString().equals("2"))
                        {
                            String t="resource";
                            List<Map<String,Object>> columns=dbService.columns(t);
                            int index=-1;
                            for(int i=0;i<columns.size();i++)
                            {
                                String field=columns.get(i).get("Field").toString();
                                if(field.equals("field_"+id))
                                {
                                    index=i;
                                    i=columns.size();
                                }
                            }
                            if(index==-1)
                            {
                            //水资源站点
                            String sql="ALTER table hnww_resource add COLUMN field_"+id+" varchar(200) not null default ''";
                            jdbcTemplate.update(sql);
                            }
                        }
                        if(ftype.toString().equals("3"))
                        {
                            String t="river";
                            List<Map<String,Object>> columns=dbService.columns(t);
                            int index=-1;
                            for(int i=0;i<columns.size();i++)
                            {
                                String field=columns.get(i).get("Field").toString();
                                if(field.equals("field_"+id))
                                {
                                    index=i;
                                    i=columns.size();
                                }
                            }
                            if(index==-1)
                            {
                            //河流
                            String sql="ALTER table hnww_river add COLUMN field_"+id+" varchar(200) not null default ''";
                            jdbcTemplate.update(sql);
                            }
                        }
                        if(ftype.toString().equals("0"))
                        {
                            String t="device";
                            List<Map<String,Object>> columns=dbService.columns(t);
                            int index=-1;
                            for(int i=0;i<columns.size();i++)
                            {
                                String field=columns.get(i).get("Field").toString();
                                if(field.equals("field_"+id))
                                {
                                    index=i;
                                    i=columns.size();
                                }
                            }
                            fileUtil.add_msg("save_after",index+"");
                            if(index==-1)
                            {
                            //用水站点
                            String sql="ALTER table hnww_device add COLUMN field_"+id+" varchar(200) not null default ''";
                            res.put("sql",sql);
                            jdbcTemplate.update(sql);
                            }
                        }
                        if(ftype.toString().equals("5"))
                        {
                            String t="deviceimg";
                            List<Map<String,Object>> columns=dbService.columns(t);
                            int index=-1;
                            for(int i=0;i<columns.size();i++)
                            {
                                String field=columns.get(i).get("Field").toString();
                                if(field.equals("field_"+id))
                                {
                                    index=i;
                                    i=columns.size();
                                }
                            }
                            if(index==-1)
                            {
                            //河流
                            String sql="ALTER table hnww_deviceimg add COLUMN field_"+id+" varchar(200) not null default ''";
                            jdbcTemplate.update(sql);
                            }
                        }
                        if(Integer.parseInt(ftype.toString())<0)
                        {
                            String t="article";
                            List<Map<String,Object>> columns=dbService.columns(t);
                            int index=-1;
                            for(int i=0;i<columns.size();i++)
                            {
                                String field=columns.get(i).get("Field").toString();
                                if(field.equals("field_"+id))
                                {
                                    index=i;
                                    i=columns.size();
                                }
                            }
                            if(index==-1)
                            {
                            //用水站点
                            String sql="ALTER table hnww_article add COLUMN field_"+id+" varchar(200) not null default ''";
                            jdbcTemplate.update(sql);
                            }
                        }
                    }
                }
            }
            else if(table.equals("planlog")&&row.get("id")==null)
            {
                Object plan_id=row.get("plan_id");
                Object state=row.get("state");
                String sql="update hnww_plan set state="+state+" where id="+plan_id;
                jdbcTemplate.update(sql);
            }
            else if(table.equals("category"))
            {
                //当删除分类时不需要传递type参数
                if(row.get("type")!=null)
                {
                    int type=Integer.parseInt(row.get("type").toString());
                    dbService.ini_category_path(type);
                }
            }
            return res;
        }
        catch (Exception ex)
        {
            fileUtil.add_msg("save_after",common.format_exception(ex));
            return res;
        }
    }
}
